<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use utils\out;

$app->get('/comment', function (Application $app, Request $request) {

	$marketid = $request->get('marketid');
	$star = $request->get('star');
	$uid = $request->get('uid');
    $uname = $request->get('name');
	$message = $request->get('message');
	$tagid = $request->get('tag');
	$marketname = $request->get('marketname');
	
//	return $app->json(array('len'=>strlen($tagid)));
	
	if(strlen($tagid)>300){
		return $app->json(['status'=>'-1', 'msg'=>'标签内容过长,不超过100字']);
	}
	
	if(strlen($message)>300){
		return $app->json(['status'=>'-1', 'msg'=>'评论内容过长,不超过100字']);
	}
	
    // 获取推荐
    $sql = "SELECT * FROM t_comment where marketid = ? and uid = ?";
	$data = $app['db']->fetchAssoc($sql, array((int)$marketid,(int) $uid));
	
//	if($data == true){
//		$result = array('status'=>'-1', 'msg'=>'您已经对该菜场做出了评价。');
//		return $app->json($result);
//	}
	
	$sql = "INSERT INTO t_comment(marketid,marketname,tagid,star,uid,uname,message,addtime) values (?,?,?,?,?,?,?,?)";
	$data = $app['db']->executeUpdate($sql, array(
			$marketid,
			$marketname,
			$tagid,
			$star,
			$uid,
			$uname,
			$message,
			time()
		));
	
	//
	
	return $app->json(array('status'=>'ok', 'msg'=>'添加成功。'));
});

$app->get('/mcomment', function (Application $app, Request $request) {
	$marketid = $request->get('marketid');
	$sql = 'select marketid,count(marketid),sum(star) from t_comment where marketid = ? GROUP BY marketid ';
	$data = $app['db']->fetchAll($sql,[(int)$marketid]);
	return $app->json(array("success"=>true, "arr"=>$data));
});


$app->get('/iscomment', function (Application $app, Request $request) {
	$marketid = $request->get('marketid');
	$uid = $request->get('uid');
	$sql = "select * from t_comment where marketid = ? and uid = ?";
	$data = $app['db']->fetchAssoc($sql, array((int)$marketid,(int) $uid));
	
	if($data == true){
		$result = array('status'=>'ok', 'result'=>'true');
		return $app->json($result);
	}
	else{
		$result = array('status'=>'ok', 'result'=>'false');
		return $app->json($result);
	}
});

